<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="selectedProjectId" placeholder="请选择" @change="handleProjectChange">
          <el-option v-for="item in options" :key="item.projectId" :label="item.projectName" :value="item.projectId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectContractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同类型" align="center" prop="contractType">
        <template slot-scope="scope">
          {{ scope.row.contractType === 1 ? '施工界面划分' : scope.row.contractType === 2 ? '合同文本' : scope.row.contractType === 3 ? '进度款支付台账' : '' }}
        </template>
      </el-table-column>
      <el-table-column label="合同名称" align="center" prop="contractName" />
      <el-table-column label="日期" align="center" prop="createtime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createtime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="查看合同内容" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 预览按钮 -->
          <el-button type="primary" @click="previewPdf(scope.row.detailUrl)">
            预览PDF
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"></pagination>

    <!-- 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择">
            <el-option v-for="item in options" :key="item.projectId" :label="item.projectName" :value="item.projectId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称"></el-input>
        </el-form-item>
        <el-form-item label="项目合同" prop="detailUrl">
          <PdfUpload v-model="form.detailUrl" :limit="1" @success="handleUploadSuccess" />
        </el-form-item>
        <el-form-item label="日期" prop="createtime">
          <el-date-picker v-model="form.createtime" type="date" placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" title="预览" width="800" append-to-body>
      <embed :src="dialogImageUrl" type="application/pdf" width="100%" height="600px" />
    </el-dialog>
  </div>
</template>

<script>
import { listProjectContract, getProjectContract, delProjectContract, addProjectContract, updateProjectContract } from "@/api/project/projectContract";
import { listProjectAllByUserId } from '@/api/project/project';
import { addDetail, getDetail, updateDetail, delDetail } from "@/api/system/detail";
import { getToken } from '@/utils/auth';
import PdfUpload from '@/components/PdfUpload/index.vue';

export default {
  name: "ProjectContract",
  components: { PdfUpload },
  data() {
    return {
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      pdfFiles: [],
      dialogVisible: false,
      dialogImageUrl: '',
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      projectContractList: [],
      title: "",
      open: false,
      viewDialogVisible: false,
      currentPdfUrl: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        contractType: null,
        contractName: null,
        createtime: null
      },
      options: [],
      form: {
        contractId: null,
        projectId: null,
        contractType: null,
        contractName: null,
        createtime: null,
        detailUrl: null
      },
      selectValue: null,
      selectedProjectId: null,
      fileList: [],
      rules: {}
    };
  },
  created() {
    this.getList();
    this.getProjectList();
  },
  methods: {
    handleProjectChange(value) {
      this.selectedProjectId = value;
      this.getList();
    },
    handleUploadSuccess(fileUrl) {
      this.form.detailUrl = fileUrl; // 保存URL到表单中
      console.log("PDF URL set to:", this.form.detailUrl);
    },
    getList() {
      this.loading = true;
      listProjectContract(this.queryParams).then(response => {
        this.projectContractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        contractId: null,
        projectId: null,
        contractType: null,
        contractName: null,
        createtime: null,
        detailUrl: null
      };
      this.fileList = [];
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目合同";
      this.form.projectId = this.selectedProjectId; // 使用选中的项目ID
    },
    handleUpdate(row) {
      this.reset();
      const contractId = row.contractId || this.ids;
      getProjectContract(contractId).then(response => {
        this.form = response.data;
        this.form.projectId = this.selectedProjectId; // 使用选中的项目ID
        console.log("Project Contract Data:", response.data);

        // 获取并设置 detailUrl
        getDetail(contractId).then(detailResponse => {
          if (detailResponse && detailResponse.data) {
            this.form.detailUrl = detailResponse.data.detailUrl;
            console.log("Detail URL:", detailResponse.data.detailUrl);
          }
        });
        this.open = true;
        this.title = "修改项目合同";
      });
    },
    previewPdf(url) {
      console.log("Preview PDF URL:", url);
      this.dialogImageUrl = encodeURI(url);
      this.dialogVisible = true;
    },
    handleView(row) {
      this.currentPdfUrl = row.detailUrl;
      this.viewDialogVisible = true;
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = {
            ...this.form,
            createtime: this.form.createtime ? this.form.createtime : null
          };
          if (formData.contractId != null) {
            updateProjectContract(formData).then(response => {
              // 保存 detailUrl 到 ProjectContractDetail 表
              this.saveDetailUrl(formData.contractId, formData.detailUrl);
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("Update failed:", error);
              this.$message.error("修改失败");
            });
          } else {
            addProjectContract(formData).then(response => {
              // 检查返回的数据是否包含 contractId
              if (response && response.data && response.data.contractId) {
                // 保存 detailUrl 到 ProjectContractDetail 表
                this.saveDetailUrl(response.data.contractId, formData.detailUrl);
                this.$message.success("新增成功");
                this.open = false;
                this.getList();
              } else {
                console.error("Add failed: contractId not found in response", response);
                this.$message.error("新增失败: 未返回合同ID");
              }
            }).catch(error => {
              console.error("Add failed:", error);
              this.$message.error("新增失败");
            });
          }
        }
      });
    },
    saveDetailUrl(contractId, detailUrl) {
      const detailData = {
        contractId: contractId,
        detailUrl: detailUrl
      };
      // 调用API保存 detailData
      addDetail(detailData).then(response => {
        console.log("Detail URL saved successfully");
      }).catch(error => {
        console.error("Failed to save detail URL:", error);
        this.$message.error("Failed to save detail URL: " + error);
      });
    },
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$confirm(`是否确认删除项目合同编号为"${contractIds}"的数据项？`).then(() => {
        return delProjectContract(contractIds);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).catch(() => {
      });
    },
    handleExport() {
      this.download('project/projectContract/export', {
        ...this.queryParams
      }, `projectContract_${new Date().getTime()}.xlsx`)
    },
    getProjectList() {
      listProjectAllByUserId().then((r) => {
        this.options = r.data;
        if (r.data.length > 0) {
          this.selectedProjectId = r.data[0].projectId;
          this.getList();
        }
      });
    }
  }
};
</script>
